package com.lvxh.exp.filter.global;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ImageServlet extends HttpServlet
{

    /**
	 * 
	 */
    private static final long serialVersionUID = 6989073930747651944L;

    public void doGet(HttpServletRequest request, HttpServletResponse response)

    throws ServletException, IOException
    {

        this.doPost(request, response);

    }

    // 生成数字和字母的验证码

    public void doPost(HttpServletRequest request, HttpServletResponse response)

    throws ServletException, IOException
    {

     // 在内存中创建图象
        int width=68, height=22;
        
        BufferedImage img = new BufferedImage(width, height,

        BufferedImage.TYPE_INT_RGB);

        // 得到该图片的绘图对象

        Graphics g = img.getGraphics();

        Random r = new Random();


        g.setColor(getRandColor(1, 255));

        
        
        
        
        // 填充整个图片的颜色

       g.fillRect(0, 0, width, height);
        //生成随机类
        Random random = new Random();

        for (int i=0;i<20;i++) {
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            int xl = random.nextInt(12);
            int yl = random.nextInt(12);
            g.drawLine(x,y,x+xl,y+yl);
        }

        // 向图片中输出数字和字母

        StringBuffer sb = new StringBuffer();

        char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();

        int index, len = ch.length;

        for (int i = 0; i < 4; i++)
        {

            index = r.nextInt(len);

            g.setColor(new Color(r.nextInt(88), r.nextInt(188), r.nextInt

            (255)));

            g.setFont(new Font("Arial", Font.BOLD | Font.ITALIC, 22));// 输出的字体和大小

            g.drawString("" + ch[index], (i * 15) + 3, 18);// 写什么数字，在图片的什么位置画

            sb.append(ch[index]);

        }

        request.getSession().setAttribute(Constant.VERIFICATION_CODE, sb.toString());

        ImageIO.write(img, "JPG", response.getOutputStream());

    }

    private Color getRandColor(int fc, int bc)
    {// 给定范围获得随机颜色
        Random random = new Random();
        if (fc > 255)
            fc = 255;
        if (bc > 255)
            bc = 255;
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }
}
